<template>
  <app-navbar />
  <div class="game-management-layout">
    <side-bar v-if="isLoggedIn" />
    <div class="game-management-view">
      <div class="actions-bar">
        <button class="add-btn" @click="openAddModal">+ 添加新游戏</button>
      </div>
      <div class="game-table">
        <div class="game-table-header">
          <span>封面</span>
          <span>游戏名称</span>
          <span>状态</span>
          <span>操作</span>
        </div>
        <div v-for="game in games" :key="game.id" class="game-table-row">
          <img :src="game.img" class="game-cover" />
          <span class="game-title">{{ game.title }}</span>
          <span>
            <span :class="['status', getStatusClass(game.status)]">{{ getStatusText(game.status) }}</span>
          </span>
          <span class="actions">
            <button @click="toggleStatus(game)" class="status-btn" v-if="game.status !== undefined">
              {{ getButtonText(game.status) }}
            </button>
            <button @click="openEditModal(game)" class="edit-btn">编辑</button>
            <button class="delete-btn">删除</button>
          </span>
        </div>
      </div>
      <!-- Pagination Controls -->
      <div v-if="totalPages > 1" class="pagination-controls">
        <button @click="goToPage(currentPage - 1)" :disabled="currentPage === 1" class="page-btn">
          上一页
        </button>
        <span>第 {{ currentPage }} / {{ totalPages }} 页</span>
        <button @click="goToPage(currentPage + 1)" :disabled="currentPage === totalPages" class="page-btn">
          下一页
        </button>
      </div>
    </div>
  </div>

  <!-- 新增/编辑游戏弹窗 -->
  <div v-if="showModal" class="modal-overlay">
    <div class="modal-content">
      <h2>{{ modalTitle }}</h2>
      <form @submit.prevent="handleSaveGame">
        <div class="form-grid">
          <div class="form-group">
            <label for="gameCode">游戏代码</label>
            <input id="gameCode" v-model="currentGame.gameCode" type="text" required />
          </div>
          <div class="form-group">
            <label for="title">游戏名称</label>
            <input id="title" v-model="currentGame.title" type="text" required />
          </div>
          <div class="form-group">
            <label for="genre">类型</label>
            <input id="genre" v-model="currentGame.genre" type="text" />
          </div>
          <div class="form-group">
            <label for="platforms">平台</label>
            <input id="platforms" v-model="currentGame.platforms" type="text" />
          </div>
          <div class="form-group">
            <label for="price">价格</label>
            <input id="price" v-model.number="currentGame.price" type="number" step="0.01" />
          </div>
          <div class="form-group">
            <label for="discountPrice">折扣价</label>
            <input id="discountPrice" v-model.number="currentGame.discountPrice" type="number" step="0.01" />
          </div>
          <div class="form-group">
            <label for="status">状态</label>
            <select id="status" v-model.number="currentGame.status">
              <option value="0">待上架</option>
              <option value="1">已上架</option>
            </select>
          </div>
          <div class="form-group full-width">
            <label for="description">描述</label>
            <textarea id="description" v-model="currentGame.description"></textarea>
          </div>
          <div class="form-group">
            <label for="onshelfDate">上架日期</label>
            <input id="onshelfDate" v-model="currentGame.onshelfDate" type="datetime-local" />
          </div>
          <div class="form-group">
            <label for="offShelfDate">下架日期</label>
            <input id="offShelfDate" v-model="currentGame.offShelfDate" type="datetime-local" />
          </div>
        </div>

        <!-- File Upload Section (only for editing) -->
        <div v-if="editingGameId" class="upload-section">
          <div class="upload-area">
            <label>封面图片</label>
            <div class="upload-controls">
              <button type="button" class="upload-btn" @click="triggerFileUpload('image')">选择文件</button>
              <button type="button" class="save-btn" @click="handleFileUpload('image')" :disabled="!selectedFiles.image">确认上传</button>
            </div>
            <input type="file" ref="imageUploader" @change="handleFileChange('image', $event)" accept="image/*" style="display: none;" />
            <span v-if="selectedFiles.image" class="file-name">{{ selectedFiles.image.name }}</span>
          </div>
          <!-- Placeholder for video upload -->
          <div class="upload-area">
            <label>宣传视频 (待开发)</label>
             <div class="upload-controls">
              <button type="button" class="upload-btn-disabled" disabled>选择文件</button>
              <button type="button" class="save-btn-disabled" disabled>确认上传</button>
            </div>
          </div>
        </div>

        <div class="modal-actions">
          <button type="submit" class="save-btn">保存文本信息</button>
          <button type="button" class="cancel-btn" @click="closeModal">取消</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import AppNavbar from '@/components/AppNavbar.vue'
import SideBar from '@/components/SideBar.vue'
import axios from '@/axios/axios'; // 引入axios实例

const isLoggedIn = ref(sessionStorage.getItem('isLoggedIn') === 'true')
const games = ref([])
const showModal = ref(false)
const modalTitle = ref('')
const currentGame = ref({})
const editingGameId = ref(null); // To track if we are editing

// File upload state
const imageUploader = ref(null);
const selectedFiles = ref({
  image: null,
  // video: null // Reserved for future
});

// Pagination state
const currentPage = ref(1);
const pageSize = ref(10);
const totalGames = ref(0);

const totalPages = computed(() => {
  return Math.ceil(totalGames.value / pageSize.value);
});

// 获取游戏列表
async function fetchGames(page = 1) {
  try {
    const response = await axios.get('/game/list', {
      params: {
        page: page,
        pageSize: pageSize.value
      }
    });
    if (response.data.code === 200 && response.data.data) {
      games.value = response.data.data.records.map(game => ({
        ...game,
        status: parseInt(game.status, 10), // Ensure status is a number
        img: game.trailerPicture || 'https://via.placeholder.com/80x80?text=No+Image' // Use trailerPicture or a placeholder
      }));
      totalGames.value = response.data.data.total;
      currentPage.value = page;
    } else {
      games.value = [];
      totalGames.value = 0;
      console.error("Failed to fetch games:", response.data.msg);
    }
  } catch (error) {
    console.error("Error fetching game list:", error);
    games.value = [];
    totalGames.value = 0;
    alert('获取游戏列表失败，请检查网络或联系管理员。');
  }
}

onMounted(() => {
  fetchGames(currentPage.value);
});

function goToPage(page) {
  if (page >= 1 && page <= totalPages.value) {
    fetchGames(page);
  }
}

const openAddModal = () => {
  editingGameId.value = null; // Ensure we are in "add" mode
  modalTitle.value = '添加新游戏';
  currentGame.value = {
    gameCode: '',
    title: '',
    description: null,
    genre: '',
    platforms: '',
    price: 0.00,
    discountPrice: null,
    rating: null,
    onshelfDate: '',
    offShelfDate: '',
    status: 0, // 0 for 待上架
  };
  selectedFiles.value = { image: null };
  showModal.value = true;
};

const openEditModal = async (game) => {
  try {
    const response = await axios.get('/game/getGameById', {
      params: { gameId: game.id }
    });

    if (response.data.code === 200 && response.data.data) {
      editingGameId.value = game.id;
      modalTitle.value = '编辑游戏';
      
      const formatDateTimeLocal = (dateString) => {
        if (!dateString) return '';
        const date = new Date(dateString);
        const timezoneOffset = date.getTimezoneOffset() * 60000;
        const localDate = new Date(date.getTime() - timezoneOffset);
        return localDate.toISOString().slice(0, 16);
      };

      currentGame.value = {
        ...response.data.data,
        status: parseInt(response.data.data.status, 10),
        onshelfDate: formatDateTimeLocal(response.data.data.onshelfDate),
        offShelfDate: formatDateTimeLocal(response.data.data.offShelfDate)
      };
      
      selectedFiles.value = { image: null }; // Reset file selection on open
      showModal.value = true;
    } else {
      alert('获取游戏详情失败: ' + (response.data.msg || '未知错误'));
    }
  } catch (error) {
    console.error('获取游戏详情失败:', error);
    alert('获取游戏详情失败，请检查网络或联系管理员。');
  }
};

const closeModal = () => {
  showModal.value = false;
};

const handleSaveGame = async () => {
  const isEditing = !!editingGameId.value;
  
  try {
    // 日期格式化逻辑 (与之前相同)
    if (currentGame.value.onshelfDate) {
      currentGame.value.onshelfDate = new Date(currentGame.value.onshelfDate).toISOString().replace('Z', '');
    }
    if (currentGame.value.offShelfDate) {
      currentGame.value.offShelfDate = new Date(currentGame.value.offShelfDate).toISOString().replace('Z', '');
    }
    
    if (isEditing) {
      //将来在这里处理编辑逻辑，例如调用 axios.put
      console.log('正在编辑游戏:', editingGameId.value, currentGame.value);
      alert('编辑功能-保存接口待实现');
      // const response = await axios.put(`/game/${editingGameId.value}`, currentGame.value);
    } else {
      // 新增逻辑
      const response = await axios.post('/game', currentGame.value);
      if (response.data.code === 200) {
        alert('游戏添加成功！');
      } else {
        alert('添加失败: ' + (response.data.msg || '未知错误'));
        return; //
      }
    }
    
    closeModal();
    fetchGames(currentPage.value); // 重新获取当前页列表

  } catch (error) {
    console.error('保存游戏失败:', error);
    alert('保存失败，请检查网络或联系管理员。');
  }
};

function toggleStatus(game) {
  // 这里之后也应该调用API
  if (game.status === 0) {
    game.status = 1; // 待上架 -> 已上架
  } else if (game.status === 1) {
    game.status = 2; // 已上架 -> 已下架
  } else if (game.status === 2) {
    game.status = 1; // 已下架 -> 已上架
  }
}

// 新增帮助函数
function getButtonText(status) {
  const map = {
    0: '上架',
    1: '下架',
    2: '上架'
  };
  return map[status] || '';
}

function getStatusText(status) {
  const map = {
    0: '待上架',
    1: '已上架',
    2: '已下架'
  };
  return map[status] || '未知';
}

function getStatusClass(status) {
  const map = {
    0: 'pending',
    1: 'on',
    2: 'off'
  };
  return map[status] || '';
}

const triggerFileUpload = (type) => {
  if (type === 'image') {
    imageUploader.value.click();
  }
  // else if (type === 'video') { ... } // Reserved
};

const handleFileChange = (type, event) => {
  const file = event.target.files[0];
  if (!file) return;
  
  if (type === 'image') {
    selectedFiles.value.image = file;
  }
  // else if (type === 'video') { ... } // Reserved
};

const handleFileUpload = async (type) => {
  if (type !== 'image' || !selectedFiles.value.image || !editingGameId.value) {
    alert('请先选择一个图片文件');
    return;
  }

  const formData = new FormData();
  formData.append('gameId', editingGameId.value);
  formData.append('file', selectedFiles.value.image);

  try {
    const response = await axios.post('/game/uploadPicture', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (response.data.code === 200) {
      alert('图片上传成功！');
      selectedFiles.value.image = null; // Clear selection
      fetchGames(currentPage.value); // Refresh list to show new image
    } else {
      alert('上传失败: ' + (response.data.msg || '未知错误'));
    }
  } catch (error) {
    console.error('上传图片失败:', error);
    alert('上传失败，请检查网络或联系管理员。');
  }
};
</script>

<style scoped>
.game-management-layout {
  display: flex;
  flex-direction: row;
  width: 100vw;
  min-height: 100vh;
  background: linear-gradient(135deg, #181a20 60%, #232946 100%);
  justify-content: center;
}
.game-management-view {
  flex: 1;
  margin-left: 180px;
  padding: 56px 0 32px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  justify-content: flex-start;
  width: 100%;
  box-sizing: border-box;
}
.game-management-view h2 {
  color: #a3b8d8;
  font-size: 2.4rem;
  margin-bottom: 36px;
  letter-spacing: 2px;
  text-shadow: 0 2px 18px #3a4a6a44, 0 0 2px #232946;
  font-weight: 700;
  transition: color 0.3s;
}
.actions-bar {
  margin-bottom: 28px;
  text-align: right;
  width: 100%;
  max-width: 1200px;
}
.add-btn {
  background: linear-gradient(90deg, #4e8cff 0%, #6ed0ff 100%);
  color: #232946;
  border: none;
  border-radius: 8px;
  padding: 10px 28px;
  font-size: 1.08rem;
  font-weight: bold;
  cursor: pointer;
  box-shadow: 0 2px 12px #4e8cff33;
  transition: background 0.3s, box-shadow 0.3s, transform 0.2s;
}
.add-btn:hover {
  background: linear-gradient(90deg, #6ed0ff 0%, #4e8cff 100%);
  box-shadow: 0 6px 24px #4e8cff66;
  transform: translateY(-2px) scale(1.04);
}
.game-table {
  background: rgba(24,26,32,0.97);
  border-radius: 24px;
  box-shadow: 0 8px 40px 0 #4e8cff22, 0 0 0 2px #232946;
  border: 1.5px solid #232946;
  padding: 0 0 18px 0;
  min-width: 90vw;
  max-width: 90vw;
  margin: 0 auto;
  transition: box-shadow 0.3s;
  padding-left: 48px;
}
.game-table-header, .game-table-row {
  display: grid;
  grid-template-columns: 100px 2fr 1fr 2.2fr;
  align-items: center;
  gap: 18px;
  padding: 20px 36px;
  text-align: center;
}
.game-table-header span, .game-table-row > * {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  width: 100%;
}
.game-table-header {
  color: #7fa7d6;
  font-weight: bold;
  font-size: 1.18rem;
  border-bottom: 2px solid #232946;
  background: rgba(35,41,70,0.92);
  border-radius: 24px 24px 0 0;
  letter-spacing: 1.5px;
}
.game-table-row {
  border-bottom: 1px solid #232946;
  background: transparent;
  transition: background 0.25s, box-shadow 0.25s, transform 0.2s;
}
.game-table-row:hover {
  background: rgba(78,140,255,0.08);
  box-shadow: 0 4px 24px #4e8cff22;
  transform: scale(1.012);
}
.game-cover {
  width: 72px;
  height: 72px;
  object-fit: cover;
  border-radius: 12px;
  border: 2px solid #232946;
  box-shadow: 0 2px 12px #4e8cff22;
  transition: box-shadow 0.3s, transform 0.2s;
}
.game-table-row:hover .game-cover {
  box-shadow: 0 6px 24px #4e8cff55;
  transform: scale(1.04);
}
.game-title {
  justify-content: center;
  align-items: center;
  display: flex;
  color: #e0e6f0;
  font-size: 1.18rem;
  font-weight: 500;
  letter-spacing: 1px;
  text-align: center;
  width: 100%;
}
.status {
  padding: 6px 18px;
  border-radius: 16px;
  font-size: 1.05rem;
  font-weight: bold;
  background: #232946;
  color: #7fa7d6;
  margin-right: 8px;
  box-shadow: 0 1px 6px #4e8cff22;
  transition: background 0.2s, color 0.2s;
}
.status.off {
  background: #444a5a;
  color: #bbb;
}
.status.pending {
  background: #a88532;
  color: #fff;
}
.actions button {
  margin-right: 10px;
  padding: 8px 18px;
  border-radius: 8px;
  border: none;
  font-size: 1.05rem;
  cursor: pointer;
  transition: background 0.2s, color 0.2s, box-shadow 0.2s, transform 0.2s;
  box-shadow: 0 1px 6px #4e8cff22;
}
.status-btn {
  background: linear-gradient(90deg, #7fa7d6 0%, #4e8cff 100%);
  color: #232946;
}
.status-btn:hover {
  background: linear-gradient(90deg, #4e8cff 0%, #7fa7d6 100%);
  color: #fff;
  box-shadow: 0 4px 16px #4e8cff55;
  transform: scale(1.05);
}
.edit-btn {
  background: #232946;
  color: #7fa7d6;
}
.edit-btn:hover {
  background: #4e8cff;
  color: #fff;
  box-shadow: 0 4px 16px #4e8cff55;
  transform: scale(1.05);
}
.delete-btn {
  background: #444a5a;
  color: #fff;
}
.delete-btn:hover {
  background: #ff4d4f;
  color: #fff;
  box-shadow: 0 4px 16px #ff4d4f55;
  transform: scale(1.05);
}
@media (max-width: 900px) {
  .game-management-view {
    padding: 24px 0 16px 0;
  }
  .game-table {
    min-width: 98vw;
    max-width: 100vw;
    border-radius: 0;
    padding-left: 0;
  }
  .game-table-header, .game-table-row {
    padding: 12px 4vw;
    grid-template-columns: 60px 1.2fr 0.8fr 1.5fr;
  }
}

/* Modal Styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1001;
}

.modal-content {
  background: #2d2d2d;
  padding: 2rem;
  border-radius: 12px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.3);
  width: 90%;
  max-width: 600px;
  color: #e0e6f0;
}

.modal-content h2 {
  color: #a3b8d8;
  margin-bottom: 1.5rem;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #7fa7d6;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 0.75rem;
  border-radius: 6px;
  border: 1px solid #232946;
  background: #181a20;
  color: #e0e6f0;
  font-size: 1rem;
  box-sizing: border-box;
}

.form-group textarea {
  min-height: 80px;
  resize: vertical;
}

.modal-actions {
  margin-top: 1.5rem;
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.save-btn, .cancel-btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.save-btn {
  background: linear-gradient(90deg, #4e8cff 0%, #6ed0ff 100%);
  color: #232946;
}

.save-btn:hover {
  box-shadow: 0 4px 15px #4e8cff66;
  transform: translateY(-2px);
}

.cancel-btn {
  background: #444a5a;
  color: #fff;
}

.cancel-btn:hover {
  background: #555c6d;
}

/* Upload Section Styles */
.upload-section {
  grid-column: 1 / -1;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
  margin-top: 1.5rem;
  border-top: 1px solid #444a5a;
  padding-top: 1.5rem;
}

.upload-area {
  display: flex;
  flex-direction: column;
}

.upload-area label {
  margin-bottom: 0.75rem;
  font-weight: 500;
  color: #7fa7d6;
}

.upload-controls {
  display: flex;
  gap: 0.5rem;
}

.upload-btn, .upload-btn-disabled {
  flex-grow: 1;
  background: #232946;
  color: #7fa7d6;
  padding: 0.75rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  text-align: center;
  transition: all 0.3s ease;
}

.upload-btn:hover {
  background: #4e8cff;
  color: #fff;
}

.upload-btn-disabled, .save-btn-disabled {
  background-color: #3a3f4b;
  color: #6a7385;
  cursor: not-allowed;
}

.file-name {
  margin-top: 0.5rem;
  font-style: italic;
  color: #a3b8d8;
  font-size: 0.9rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* Pagination Styles */
.pagination-controls {
  margin-top: 2rem;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  color: #a3b8d8;
}

.page-btn {
  padding: 0.5rem 1rem;
  border: 1px solid #4e8cff;
  background-color: transparent;
  color: #4e8cff;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-btn:hover:not(:disabled) {
  background-color: #4e8cff;
  color: #fff;
}

.page-btn:disabled {
  border-color: #444a5a;
  color: #444a5a;
  cursor: not-allowed;
}
</style> 